const async = require("async");
module.exports = {
    open:false,
    description: '点赞或取消点赞',
    handler(req, res, next) {
        let doc = req.body;
        let id = doc._id;//卡片ID
        let likeID = doc.likeID;//点赞者ID
        async.auto([
                callback => req.mongo.collection("card").aggregate([
                    {$unwind: "$likeID"},
                    {$match: {"_id": id, "likeID": likeID}}
                ]).toArray(callback)
            ],
            (error, re) => {
                if (error) return res.err.mongoError(error)
                if (re[0].length <= 0) {//如果查询不到结果
                    req.mongo.collection("card").updateOne(
                        {"_id": id},
                        {$push: {"likeID": likeID}},
                        {upsert: true},
                        (e, r) => {
                            if (e) return res.err.mongoError(e)
                            return res.reply({"code": 1008, "msg": "点赞成功！"})

                        }
                    )
                } else {
                    req.mongo.collection("card").updateOne(
                        {"_id": id},
                        {$pull: {"likeID": likeID}},
                        (e, r) => {
                            if (e) return res.err.mongoError(e)
                            return res.reply({"code": 1008, "msg": "取消点赞成功！"})
                        }
                    )
                }
            })
    }
}